package com.hc.appanimal;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLDecoder;
import java.util.ArrayList;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.hc.DTO.MessageDTO;
import com.hc.DTO.TokenDTO;
import com.hc.adapter.DetailMessagesAdapter;
import com.hc.constants.Constants;
import com.hc.model.utils.TokenModel;
import com.hc.webservice.InternetUtils;
import com.nostra13.universalimageloader.cache.disc.naming.Md5FileNameGenerator;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.QueueProcessingType;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.drawable.AnimationDrawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.GridView;
import android.widget.TextView;

public class DetailMessagesActivity extends Activity implements OnClickListener {
	TextView txtDesc, txtFirstName, txtUpdatedOn;
	TextView txtTitle;
	Button btnBack;
	GridView grid;
	DetailMessagesAdapter adapter;
	ArrayList<String> filePath;
	ArrayList<MessageDTO> arrMess;
	Dialog dialog;
	AnimationDrawable frameAnimation;
	Integer keyNo;

	@SuppressLint({ "NewApi", "SimpleDateFormat" })
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		filePath = new ArrayList<String>();
		setContentView(R.layout.activity_detail_messages);
		txtDesc = (TextView) findViewById(R.id.txtDesc);
		txtFirstName = (TextView) findViewById(R.id.txtFirstName);
		txtUpdatedOn = (TextView) findViewById(R.id.txtUpdatedOn);
		txtTitle = (TextView) findViewById(R.id.txtTitle);
		txtTitle.setTextSize(15.0f);
		txtTitle.setText("Message");
		btnBack = (Button) findViewById(R.id.btnBack);
		btnBack.setVisibility(View.VISIBLE);
		btnBack.setOnClickListener(this);
		Intent intent = getIntent();
		Bundle bundle = intent.getExtras();
		if (bundle != null) {
			keyNo = bundle.getInt("key");
			if (keyNo == 1) {
				if (InternetUtils.getInstance().isConnectingToInternet(this)) {
					new AsystaskLogin(this).execute();
					new VerySlowTask().execute();
				} else {
					Intent intent1 = new Intent(DetailMessagesActivity.this,
							Main.class);
					startActivity(intent1);
					finish();
				}

			} else if (keyNo == 2) {
				MessageDTO messDTO = (MessageDTO) bundle
						.getSerializable("detailmess");
				String FirstNameLastName = "";

				if (!messDTO.getLastName().equalsIgnoreCase(""))
					FirstNameLastName = messDTO.getFirstName();
				if (!messDTO.getLastName().equalsIgnoreCase(""))
					FirstNameLastName += " " + messDTO.getLastName();

				txtFirstName.setText("By: " + FirstNameLastName);

				if (!messDTO.getDescription().equalsIgnoreCase(""))
					txtDesc.setText(messDTO.getDescription());
				String date = "";
				String datefinal = "";
				if (!messDTO.getUpdatedOn().equalsIgnoreCase("")) {
					date = messDTO.getUpdatedOn();
					String year = date.substring(0, 4);
					String mon = date.substring(5, 7);
					String day = date.substring(8, 10);
					int hour = Integer.parseInt(date.substring(11, 13));
					String minutes = date.substring(14, 16);

					datefinal = day + "-" + mon + "-" + year;
					if (hour <= 12) {
						datefinal = "Sent on: " + day + "-" + mon + "-" + year
								+ " " + hour + ":" + minutes + " AM";
					} else {
						datefinal = "Sent on: " + day + "-" + mon + "-" + year
								+ " " + hour + ":" + minutes + " PM";
					}
				}
				txtUpdatedOn.setText(datefinal);
				try {
					filePath = messDTO.getFilePath();
					if (filePath.size() > 0) {
						for (String string : filePath) {
							TextView textView = new TextView((Context) this);
							textView.setTextSize(14.0F);
							textView.setText(string);
							textView.setWidth(100);
							textView.setHeight(200);

						}
						grid = (GridView) findViewById(R.id.grid);
						DisplayMetrics dm = new DisplayMetrics();
						getWindowManager().getDefaultDisplay().getMetrics(dm);
						int width = dm.widthPixels;
						int height = dm.heightPixels;
						int dens = dm.densityDpi;
						double wi = (double) width / (double) dens;
						double hi = (double) height / (double) dens;
						double x = Math.pow(wi, 2);
						double y = Math.pow(hi, 2);
						double screenInches = Math.sqrt(x + y);

						if (screenInches >= 4.0) {
							grid.setNumColumns(3);
						} else {
							grid.setNumColumns(2);
						}
						initImageLoader(getApplicationContext());
						adapter = new DetailMessagesAdapter(
								DetailMessagesActivity.this, R.layout.grid_row,
								filePath);
						grid.setAdapter(adapter);
					}
				} catch (Exception e) {
					// TODO: handle exception
				}
			}
		}

		// txtLinkImg.setText(messDTO.getFilePath());

	}

	public class VerySlowTask extends AsyncTask<Void, Void, Void> {
		TokenModel tokenModel = TokenModel.getInstance();
		TokenDTO token = tokenModel.getToken(DetailMessagesActivity.this);
		String t = "";
		boolean flag = false;
		String FirstName;
		String LastName;
		MessageDTO mesDTO;

		public VerySlowTask() {
			dialog = new Dialog(DetailMessagesActivity.this, R.style.NewDialog);
			dialog.setContentView(R.layout.loading);

			dialog.setCancelable(false);
			dialog.findViewById(R.id.loading_icon).setBackgroundResource(
					R.drawable.spin_animation);
			frameAnimation = (AnimationDrawable) dialog.findViewById(
					R.id.loading_icon).getBackground();
			dialog.show();
			frameAnimation.start();
		}

		@Override
		protected Void doInBackground(Void... params) {
			HttpEntity httpEntity = null;
			HttpClient client = new DefaultHttpClient();
			HttpGet method = new HttpGet(Constants.URL_GET_ALL_PUSH_DATA);
			method.setHeader("Content-Type",
					"application/x-www-form-urlencoded;charset=UTF-8");
			method.setHeader("Authorization", token.getToken_type() + " "
					+ token.getAccess_token());

			HttpResponse response;
			try {
				mesDTO = new MessageDTO();
				response = client.execute(method);
				httpEntity = response.getEntity();
				String strJson = EntityUtils.toString(httpEntity);

				if (strJson != null) {
					JSONArray jsonArr = new JSONArray(strJson);
					JSONObject obj = jsonArr
							.getJSONObject(jsonArr.length() - 1);

					if (obj.has("DescExp")) {
						String DescExp = obj.getString("DescExp");
						mesDTO.setDescExp(DescExp);
					}
					if (obj.has("UpdatedOn")) {
						String UpdatedOn = obj.getString("UpdatedOn");
						mesDTO.setUpdatedOn(UpdatedOn);
					}
					if (obj.has("Description")) {
						String Description = obj.getString("Description");
						mesDTO.setDescription(Description);
					}

					JSONArray arrPushDataIs = obj.getJSONArray("PushDataIs");
					int dem = 0;
					ArrayList<String> pathImg = new ArrayList<String>();
					for (int j = 0; j < arrPushDataIs.length(); j++) {
						JSONObject jsonPushDataIs = arrPushDataIs
								.getJSONObject(j);

						if (jsonPushDataIs.has("FilePath")) {
							String FilePath = jsonPushDataIs
									.getString("FilePath");
							pathImg.add(FilePath);
							mesDTO.setFilePath(pathImg);
						}
						dem++;
					}
					if (dem > 0) {
						mesDTO.setCount(dem);
					}

					JSONObject objUser = obj.getJSONObject("User");

					if (objUser.has("FirstName")) {
						FirstName = objUser.getString("FirstName");
						mesDTO.setFirstName(FirstName);
					}
					if (objUser.has("LastName")) {
						LastName = objUser.getString("LastName");
						mesDTO.setLastName(LastName);
					}

					// if (mesDTO != null) {
					// arrMess.add(mesDTO);
					// }

				}
			} catch (ClientProtocolException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (JSONException e) {
				flag = true;
				e.printStackTrace();
			}

			return null;
		}

		@Override
		protected void onPostExecute(Void result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			dialog.dismiss();
			frameAnimation.stop();
			String FirstNameLastName = "";
			if (!mesDTO.getLastName().equalsIgnoreCase(""))
				FirstNameLastName = mesDTO.getFirstName();
			if (!mesDTO.getLastName().equalsIgnoreCase(""))
				FirstNameLastName += " " + mesDTO.getLastName();
			txtFirstName.setText("By: " + FirstNameLastName);
			txtDesc.setText(mesDTO.getDescription());
			String date = "";
			String datefinal = "";
			if (!mesDTO.getUpdatedOn().equalsIgnoreCase("")) {
				date = mesDTO.getUpdatedOn();
				String year = date.substring(0, 4);
				String mon = date.substring(5, 7);
				String day = date.substring(8, 10);
				int hour = Integer.parseInt(date.substring(11, 13));
				String minutes = date.substring(14, 16);

				datefinal = day + "-" + mon + "-" + year;
				if (hour <= 12) {
					datefinal = "Sent on: " + day + "-" + mon + "-" + year
							+ " " + hour + ":" + minutes + " AM";
				} else {
					datefinal = "Sent on: " + day + "-" + mon + "-" + year
							+ " " + hour + ":" + minutes + " PM";
				}
			}
			txtUpdatedOn.setText(datefinal);
			try {
				filePath = mesDTO.getFilePath();
				if (filePath.size() > 0) {

					grid = (GridView) findViewById(R.id.grid);
					DisplayMetrics dm = new DisplayMetrics();
					getWindowManager().getDefaultDisplay().getMetrics(dm);
					int width = dm.widthPixels;
					int height = dm.heightPixels;
					int dens = dm.densityDpi;
					double wi = (double) width / (double) dens;
					double hi = (double) height / (double) dens;
					double x = Math.pow(wi, 2);
					double y = Math.pow(hi, 2);
					double screenInches = Math.sqrt(x + y);

					if (screenInches >= 4.0) {
						grid.setNumColumns(3);
					} else {
						grid.setNumColumns(2);
					}
					initImageLoader(getApplicationContext());
					adapter = new DetailMessagesAdapter(
							DetailMessagesActivity.this, R.layout.grid_row,
							filePath);
					grid.setAdapter(adapter);
				}
			} catch (Exception e) {
				// TODO: handle exception
			}

		}

	}

	static String baseNameFromURL(URL url) {
		String shortName;
		String path = url.getPath();
		String escaped = path.substring(path.lastIndexOf('/') + 1);
		try {
			shortName = URLDecoder.decode(escaped, "UTF-8");
		} catch (UnsupportedEncodingException e) {
			throw new Error(e.getMessage(), e);
		}
		int period = shortName.lastIndexOf('.');
		return period > -1 ? shortName.substring(0, period) : shortName;
	}

	@Override
	public void onConfigurationChanged(Configuration newConfig) {
		super.onConfigurationChanged(newConfig);

		// Checks the orientation of the screen
		if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
			grid.setNumColumns(3);

		} else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT) {
			DisplayMetrics dm = new DisplayMetrics();
			getWindowManager().getDefaultDisplay().getMetrics(dm);
			int width = dm.widthPixels;
			int height = dm.heightPixels;
			int dens = dm.densityDpi;
			double wi = (double) width / (double) dens;
			double hi = (double) height / (double) dens;
			double x = Math.pow(wi, 2);
			double y = Math.pow(hi, 2);
			double screenInches = Math.sqrt(x + y);

			if (screenInches >= 4.0) {
				grid.setNumColumns(3);
			} else {
				grid.setNumColumns(2);
			}
		}
	}

	public static void initImageLoader(Context context) {
		// This configuration tuning is custom. You can tune every option, you
		// may tune some of them,
		// or you can create default configuration by
		// ImageLoaderConfiguration.createDefault(this);
		// method.
		ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(
				context).threadPriority(Thread.NORM_PRIORITY - 2)
				.denyCacheImageMultipleSizesInMemory()
				.diskCacheFileNameGenerator(new Md5FileNameGenerator())
				.diskCacheSize(50 * 1024 * 1024)
				// 50 Mb
				.tasksProcessingOrder(QueueProcessingType.LIFO)
				.writeDebugLogs() // Remove for release app
				.build();
		// Initialize ImageLoader with configuration.
		ImageLoader.getInstance().init(config);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btnBack:
			if (keyNo == 1) {
				Intent intent = new Intent(DetailMessagesActivity.this,
						Main.class);
				startActivity(intent);
				finish();
			} else if (keyNo == 2) {
				finish();
			}

			break;

		default:
			break;
		}

	}

}
